package com.secret.chain.secretchain.service.impl;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.secret.chain.secretchain.constant.MessageConstant;
import com.secret.chain.secretchain.domain.dto.UserLoginDTO;
import com.secret.chain.secretchain.domain.entity.User;
import com.secret.chain.secretchain.exception.LoginFailedException;
import com.secret.chain.secretchain.mapper.UserMapper;
import com.secret.chain.secretchain.propreties.WeChatProperties;
import com.secret.chain.secretchain.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        log.info("开始微信登录，code: {}", userLoginDTO.getCode());

        try {
            String openid = getOpenid(userLoginDTO.getCode());
            log.info("获取到 openid: {}", openid);

            if (openid == null || openid.isEmpty()) {
                throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
            }

            // 判断当前用户是否为新用户
            User user = userMapper.getByOpenid(openid);

            if (user == null) {
                user = User.builder()
                        .openid(openid)
                        .name("") // 默认值
                        .phoneNumber("") // 设置默认值或占位符
                        .userAvatar("") // 默认值
                        .createTime(LocalDateTime.now())
                        .build();
                userMapper.insert(user);
                log.info("新用户注册成功，openid: {}", openid);
            } else {
                log.info("用户已存在，openid: {}", openid);
            }

            return user;
        } catch (Exception e) {
            log.error("微信登录失败", e);
            throw new LoginFailedException("微信登录失败：" + e.getMessage());
        }
    }

    @Override
    public User queryById(Integer id) {
        log.info("Querying user by ID: {}", id);
        return userMapper.queryById(id); // 使用 MyBatis Plus 或其他 ORM 框架的方法
    }

    @Override
    public void updateUserInfo(User user) {
        log.info("Updating user info: {}", user);
        userMapper.updateUserInfo(user); // 假设你使用的是 MyBatis Plus
    }

    private String getOpenid(String code) {
        // 调用微信接口服务，获得当前微信用户的 openid
        Map<String, Object> params = new HashMap<>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");

        log.info("调用微信 API 请求参数: {}", params);

        String response = HttpUtil.get(WX_LOGIN, params);
        JSONObject jsonObject = JSON.parseObject(response);
        log.info("调用微信 API 响应: {}", jsonObject.toJSONString());

        if (jsonObject.containsKey("errcode")) {
            log.error("调用微信 API 失败: {}", jsonObject.toJSONString());
            throw new LoginFailedException("调用微信 API 失败：" + jsonObject.getString("errmsg"));
        }

        String openid = jsonObject.getString("openid");
        if (openid == null || openid.isEmpty()) {
            throw new LoginFailedException("无法获取 openid");
        }

        return openid;
    }
}